<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    //归并排序
function mergeSort(arr){
    if(arr.length<2) return arr
    let mid = Math.floor(arr.length/2)
    let left = arr.slice(0,mid)
    let right = arr.slice(mid)
    return merge(mergeSort(left),mergeSort(right))
}
function merge(left,right){
    let result = []
    while(left.length&&right.length){
        if(left[0]<right[0]){
            result.push(left.shift())
        }else{
            result.push(right.shift())
        }
    }
    while(left.length){
        result.push(left.shift())
    }
    while(right.length){
        result.push(right.shift())
    }
    return result
}

//归并实现 二维有序数组转一维有序数组

function mergeArr(arr){
    if(arr.length<=1) return arr[0]
    let mid = Math.floor(arr.length/2)
    let left = arr.slice(0,mid)
    let right = arr.slice(mid)
    return mergeSortArr(mergeArr(left),mergeArr(right))
}
function mergeSortArr(left,right){
    let result = []
    let i =0,j=0
    const len1 = left.length;
    const len2 = right.length;
    while(i<len1&&j<len2){
        if(left[i]<right[j]){
            result.push(left[i])
            i++
        }else{
            result.push(right[j])
            j++
        }
    }
    if(i<len1){
        result = result.concat(left.slice(i))
    }
    if(j<len2){
        result = result.concat(right.slice(j))
    }
    return result
}
var arr1=[[1,2,4],[2,3,7],[3,5,7],[4,5,8]]
console.log(mergeArr(arr1))
</script>

</html>